package com.java.yz.day05.homework;

/*
    实现冒泡排序，二分查找，自己输入数据进去数组
 */
import java.util.Scanner;
public class Text4 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请你输入该数组的长度：");
        int num = sc.nextInt();
        int[] array =new int[num];
        for (int i = 0; i < array.length; i++) {
            System.out.println("请输入第"+(i+1)+"个元素");
            int yuansu = sc.nextInt();
            array[i]=yuansu;
        }
        System.out.println("排序之前：");
        ArrayPrint(array);
        //输入之后现在对该数组进行排序
        maopao(array);
        System.out.println("排序之后：");
        ArrayPrint(array);

       //排完序之后就可以进行二分查找
        System.out.println("请输入你想要查找的元素");
        int num1 = sc.nextInt();

        erfen(array,num1);

    }
    //在进行封装一个排序的算法，冒泡排序
    public static void maopao(int[] array){
        for (int i = 0; i <array.length-1 ; i++) {
            for (int j = 0; j < array.length-i-1; j++) {
                int temp;
                if (array[j]>array[j+1]) {
                    temp=array[j];
                    array[j]=array[j+1];
                    array[j+1]=temp;
                }
            }
        }
    }
    //这是遍历的方法
    public static void ArrayPrint(int[] array){
        for (int i = 0; i < array.length; i++) {
            if(i==0){
                System.out.print("["+array[0]+",");
            }
            else if (i==array.length-1){
                System.out.println(array[array.length-1]+"]");
            }
            else {
                System.out.print(array[i]+",");
            }
        }
    }

    //二分查找
    public static void erfen(int[] array,int num1){
        int front=0;
        int end= array.length-1;
        Boolean flag=true;
        while(front<=end){
            int mid=(front+end)/2;
            if (array[mid]<num1){
                front=mid+1;
            }
            else if (array[mid]>num1) {
                end=mid-1;
            }
            else {
                System.out.println("你要的目标元素找到了，下标是："+mid);
                flag=false;
                break;
            }
        }
        if (flag){
            System.out.println("你查找的元素不在！");
        }
    }

}
